<template>
    <a-modal :title="title"
             :visible="visible"
             @cancel="handleCancel"
             :width="600">
        <template slot="footer">
            <div class="drawer-bootom-button">
                <a-popconfirm title="确定放弃编辑？"
                              @confirm="handleCancel"
                              okText="确定"
                              cancelText="取消">
                    <a-button key="back">关闭</a-button>
                </a-popconfirm>
                <a-button key="submit"
                          type="primary"
                          :loading="loading"
                          @click="handleOk">保存</a-button>
            </div>
        </template>
        <a-form :form="form"
                :colon="false"
                labelAlign="right">
            <a-form-item label="轮播图名称"
                         :label-col="labelCol"
                         :wrapper-col="wrapperCol">
                <a-input v-decorator="[ 'title', validatorRules.title]"
                         placeholder="请输入轮播图名称!" />
            </a-form-item>
            <a-form-item label="跳转链接"
                         :label-col="labelCol"
                         :wrapper-col="wrapperCol">
                <a-input v-decorator="[ 'targetUrl', validatorRules.targetUrl]"
                         placeholder="请输入跳转链接!"></a-input>
            </a-form-item>
            <a-form-item label="顺序"
                         :label-col="labelCol"
                         :wrapper-col="wrapperCol">
                <a-input-number v-decorator="[ 'order', validatorRules.order]"
                                placeholder="请选择顺序"
                                :min="1"
                                :max="100"
                                style="width:100%" />
            </a-form-item>
            <a-form-item label="状态"
                         :label-col="labelCol"
                         :wrapper-col="wrapperCol">
                <a-select placeholder="请选择状态!"
                          v-decorator="[ 'state', validatorRules.state]">
                    <a-select-option value="0">
                        已删除
                    </a-select-option>
                    <a-select-option value="1">
                        正常
                    </a-select-option>
                </a-select>
            </a-form-item>
            <a-form-item label="封面"
                         :label-col="labelCol"
                         :wrapper-col="wrapperCol">
                <div>
                    <a-upload v-decorator="[ 'imageUrl', validatorRules.imageUrl]"
                              v-if="path ==''"
                              list-type="text"
                              :limit="1"
                              :show-upload-list="false"
                              :customRequest="selfUpload"
                              :before-upload="beforeUpload">
                        <div>
                            <a-button type="primary"
                                      icon="upload">
                                上传
                            </a-button>
                        </div>
                    </a-upload>
                    <img v-else
                         class="img-box"
                         :src="path" @click="clearImgPath">
                </div>
            </a-form-item>

        </a-form>
    </a-modal>
</template>

<script>
import { postLoop, updateLoop, imgUpload } from '@/api/api';
import pick from "lodash/pick";
export default {
    data() {
        return {
            title: '',
            visible: false,
            model: {},
            id: '',
            form: this.$form.createForm(this),
            loading: false,
            path: '',
            labelCol: { span: 4 },
            wrapperCol: { span: 20 },
            validatorRules: {
                title: {
                    rules: [{
                        required: true,
                        message: '请输入轮播图名称!',
                    }]
                },
                targetUrl: {
                    rules: [{
                        required: true,
                        message: '请输入跳转链接!',
                    }]
                },
                order: {
                    rules: [{
                        required: true,
                        message: '请输入排序!',
                    }]
                },
                state: {
                    rules: [{
                        required: true,
                        message: '请选择状态!',
                    }]
                },
                imageUrl: {
                    rules: [{
                        required: true,
                        message: '请上传封面图片!',
                    }]
                }
            },
        }
    },
    methods: {
        add() {
            this.edit({});
        },
        edit(record) {
            this.visible = true;
            this.form.resetFields();
            this.model = Object.assign({}, record);
            if (record.imageUrl) {
                this.path = record.imageUrl;
                console.log("🚀 ~ file: AddLooper.vue ~ line 109 ~ edit ~ this.path", this.path)
            }
            this.$nextTick(() => {
                this.form.setFieldsValue(pick(record, 'title', 'targetUrl', 'order', 'state'))
            });
            this.id = record.id;
        },
        handleOk() {
            this.form.validateFields((err, values) => {
                if (!err) {
                    this.loadingOk = true;
                    let img = {
                        imageUrl: this.path
                    }
                    let formData = Object.assign(this.model, values, img);
                    let requestFn;
                    if (!this.model.id) {//新增
                        this.loading = true;
                        requestFn = postLoop(formData).then(res => {
                            if (res.code === 200) {
                                this.loading = false;
                                this.$message.success("添加成功!");
                                this.$emit('ok');
                                this.visible = false;
                            }
                        })
                    } else {//编辑
                        requestFn = updateLoop(this.id, formData).then(res => {
                            if (res.code === 200) {
                                this.loading = false;
                                this.$message.success("操作成功!");
                                this.$emit('ok');
                                this.visible = false;
                            }
                        })
                    }
                }
            });
        },
         //点击图片时清空路径显示上传按钮
        clearImgPath(){
            this.path="";
        },

        handleCancel(e) {
            this.path = '';
            this.visible = false;
        },
        selfUpload(data) {
            const formData = new FormData()
            formData.append('file', data.file)
            imgUpload(formData, 'loop').then(res => {
                if (res.code === 200) {
                    this.path = res.data;

                }
            })
        },
        beforeUpload(file) {
            const isJpgOrPng = file.type === 'image/jpeg'
                || file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/gif';
            if (!isJpgOrPng) {
                this.$message.error('您只能上传图片!');
            }
            const isLt2M = file.size / 1024 / 1024 < 50;
            if (!isLt2M) {
                this.$message.error('图片不能大于1M');
            }
            return isJpgOrPng && isLt2M;
        },
    },
}
</script>

<style>
.img-box {
    width: 180px;
    height: 60px;
    max-width: 180px;
    border-radius: 5px;
    border: 1px #5ea4e3 solid;
}
</style>